<script setup>
/**
 * & 文件引入区域
 */
import { onBeforeMount, reactive, ref } from "vue";

import { ToastFun } from "@/hook/toast";
import { getJWTFun } from "@/hook/jsrsasign";

import {
  getInfoAPI,
  publishTradition,
  selectAllTradinRate,
  countOderApi,
} from "@/server/api/userInfo";

import { useUseStore } from "@/stores/user";
import { exchange } from "@/stores/exchange";
import { useIndexStore } from "@/stores/indexStore";
import { useI18n } from "vue-i18n";
const { t } = useI18n();


/**
 * & 变量声明区
 */
let moreBoxShow = ref(false);
let userBalance = ref(); // 用户余额
let isReverse = ref(false); // 切换交易方法
let isConfirm = ref(false); // 确认发布弹出层
let address = ref(""); // 交易地址
const pattern = /^(?!.*\.$)\d+(?:\.\d+)?$/; // 匹配数字的正则
let list = ref(); // 数据列表

// 发布交易接口请求体
let publishTraReq = reactive({
  publisherId: useUseStore().userId,
  typeId: null, // 0为pi币交易积分，1为积分交易pi币
  content: "",
  pointBalance: "",
  piBalance: "",
});

//点击Pi 还是点击 eCNY
const marker = ref(1);

//获取未完成订单
const orderCount = ref(0);

//控制兑换框的改变
const showDiv = ref(true);

//上传收款码
const FileList = ref([]);

/**
 * & 函数区
 */
//搜索框
const searchData = ref("");

// 发布交易接口
const publishTraditionFun = async () => {
  console.log(isReverse.value, "ptvptv");
  console.log(showDiv.value, "svsvsvvs");
  // 关闭弹出层
  isConfirm.value = false;

  const toast = () => {
    ToastFun("", {});
  };
  if (publishTraReq.piBalance <= 0 || publishTraReq.pointBalance <= 0) {
    ToastFun("fail", { msg: t("item.details.dataException") });
    return
  }
  // 判断输入的值是否符合正则
  if (!pattern.test(publishTraReq.piBalance)) {
    publishTraReq.piBalance = "";
    toast();
    return;
  }

  if (!pattern.test(publishTraReq.pointBalance)) {
    publishTraReq.pointBalance = "";
    toast();
    return;
  }

  ToastFun("Loading", { duration: 1000 }); // 轻提示

  // 如果交易方式为积分换pi，判断用户积分余额是否足够
  if (isReverse.value) {

    if (userBalance.value < Number(publishTraReq.pointBalance)) {
      ToastFun("show", { msg: t("order.tips2") });
      return;
    }
    if (address.value == "") {
      ToastFun("show", { msg: t("item.details.EnterPiAddress") });
      return
    }
    publishTraReq.piAddress = address.value
  }

  // 判断交易方式,修改请求头
  if (showDiv.value) {
    publishTraReq.typeId = isReverse.value ? 1 : 0;
    publishTraReq.content = isReverse.value ? "我要Pi" : "我要积分";
  } else {
    if (exchange().getTraListReq.typeId == 2) {
      publishTraReq.typeId = 2;//2把积分给人家，自己拿钱
      publishTraReq.content = "我要货币";
    }
  }

  // 确认好后生成token
  const token = getJWTFun(publishTraReq);

  // 请求接口
  let res = await publishTradition(token);
  // console.log(res);

  if (res.data.code == 200) {
    // 轻提示
    ToastFun("", {});

    // 清空input
    publishTraReq.piBalance = "";
    publishTraReq.pointBalance = "";

    // 发布成功重新获取用户订单
    exchange().isCuRequire = true;

    // 重新获取数据
    list.value.changeTypeFun(publishTraReq.typeId);
  } else {
    // 轻提示
    ToastFun("", {});
  }
};

// 获取用户余额
const getBalanceFun = async () => {
  let { data } = await getInfoAPI(useUseStore().userId);

  if (data.code == 200) {
    userBalance.value = data.data;
    // console.log("用户余额", userBalance.value);
  } else {
    ToastFun("", {});
  }
};

// 修改交易类型更新列表方法
const changeTypeFun = (id) => {
  list.value.changeTypeFun(id);
};

//获取未完成的订单
const countOrder = async () => {
  const res = await countOderApi();
  if (res.data.code == 200) {
    orderCount.value = res.data.data;
  }
};

//点击了“currency之后”
const updatePage = (list) => {
  list.changeTypeFun(2);
  // 判断是不是业务员
  if (useUseStore().userInfo.level == 2) {
    showDiv.value = false;
  }
}

const selectByPiName = () => {
  exchange().getTraListReq.piName = searchData.value;
  exchange().isCuRequire = true
  list.value.changeTypeFun(exchange().getTraListReq.typeId);
}

// 生命周期
onBeforeMount(() => {
  getBalanceFun();
  // countOrder();
});

</script>

<template>
  <div class="ExchangePage">
    <div class="top">
      <TopBar :type="2">
        <div class="title">{{ $t("exchange.title") }}</div>
        <img :src="useUseStore().userInfo.userImage || '/images/pipayshop_logo.png'" alt="" class="avatar"
          @click="moreBoxShow = !moreBoxShow" />
      </TopBar>
      <!--点击头像出现的菜单 -->
      <div class="moreBox" v-show="moreBoxShow">
        <!-- 个人订单 -->
        <div class="item" @click="$router.push('/exchangeMyOrder')">
          <div class="text">{{ $t("exchange.order") }}</div>
          <!-- 正在处于交易中的订单数量 -->
          <div class="num" v-if="orderCount ? true : false">{{ orderCount }}</div>
        </div>
        <!-- 我发布的交易 -->
        <div class="item" @click="$router.push('/myTransactions')">
          <div class="text">
            {{ $t("exchangeTitle") }}
          </div>
        </div>
      </div>
      <!-- 用户的可用积分 -->
      <div class="info" v-if="userBalance">
        <!-- <div class="balance">Pi: {{ userBalance.piBalance }}</div> -->
        <div class="integral">eCNY:{{ userBalance.pointBalance }}</div>
      </div>
    </div>

    <!-- pi换积分，积分换pi的转换框 -->
    <div class="main" v-if="showDiv">
      <div :class="['convert', isReverse ? 'reverse' : '']">
        <div class="item">
          <div class="title">Pi</div>
          <input type="text" v-model="publishTraReq.piBalance" />
        </div>

        <img @click="isReverse = !isReverse;" src="/images/Me/returnLogo.png" alt="" class="logo" />

        <div class="item">
          <div class="title currency">eCNY</div>
          <input type="text" v-model="publishTraReq.pointBalance" />
        </div>
      </div>

      <div class="address" v-if="isReverse">
        <span>{{ $t("exchange.address") }}:</span>
        <input type="text" v-model="address" :placeholder="$t('exchange.addressTips')" />
      </div>

      <!-- <ForexList /> -->
      <div class="submit" @click="isConfirm = true">
        {{ $t("exchange.publish") }}
      </div>
    </div>

    <!-- eCNY换钱框 -->
    <div class="main" v-else="!showDiv">
      <div :class="['convert', isReverse ? 'reverse' : '']">
        <div class="item">
          <div class="title">eCNY</div>
          <input type="text" v-model="publishTraReq.pointBalance" />
        </div>

        <img src="/images/Me/returnLogo.png" alt="" class="logo" />
        <!-- <img @click="isReverse = !isReverse" src="/images/Me/returnLogo.png" alt="" class="logo" /> -->

        <div class="item">
          <div class="title currency">Currency</div>
          <input type="text" v-model="publishTraReq.piBalance" />
        </div>
      </div>
      <!-- 收款码 存在address字段  先不传吧，先在交易支付那个页面写死图片-->
      <!-- <div class="address" v-if="!isReverse">
        <van-field name="uploader" label="上传收款码图片">
          <template #input>
            <van-uploader v-model="FileList" :maxCount="1" :afterRead="uploadePaymentCode" />
          </template>
</van-field>
</div> -->

      <!-- <ForexList /> -->

      <!-- 发布按钮 -->
      <div class="submit" @click="isConfirm = true">
        {{ $t("exchange.publish") }}
      </div>
    </div>
    <!-- 搜索框 -->
    <div class="searchDiv">
      <input :placeholder="$t('searchName')" v-model="searchData" @keyup.enter="selectByPiName" />
      <!-- <input :placeholder="$t('searchName')" v-model="searchData" @blur="selectByPiName"
        @keyup.enter="selectByPiName" /> -->
    </div>
    <!-- 交易广场 -->
    <div class="square">
      <div class="title">{{ $t("exchange.square") }}</div>
      <!-- pi eCNY Currency -->
      <div class="tabs">
        <div class="tab">
          <!-- Pi -->
          <div @click="list.changeTypeFun(0); marker = 0; showDiv = true" :class="[
            'item',
            exchange().getTraListReq.typeId == 0 ? 'con' : '',
            useIndexStore().isRtl ? 'is_rtl' : '',
          ]">
            Pi
          </div>
          <!-- eCNY -->
          <div @click="list.changeTypeFun(1); marker = 1; showDiv = true"
            :class="['item', exchange().getTraListReq.typeId == 1 ? 'con' : '']">
            eCNY
          </div>
          <!-- 现金换积分 -->
          <div style="margin-left: 13px;" @click="updatePage(list); marker = 2;"
            :class="['item', exchange().getTraListReq.typeId == 2 ? 'con' : '']">
            Currency
          </div>
        </div>

        <div class="choose">
          <span>{{ $t("exchange.unit") }}:</span>
          <div class="type">eCNY</div>
          <!-- <img src="/images/Me/交易所icon.png" alt="" class="btn" /> -->
        </div>
      </div>

      <!-- 列表 -->
      <div class="list">
        <!-- 组件 -->
        <ExchangeOrderCom ref="list" :type="'list'" :keyWord="searchData" />
      </div>
    </div>

    <van-popup v-model:show="isConfirm" round class="isConfirm">
      <div class="title">{{ $t("exchange.isPublish") }}</div>
      <div class="btn">
        <div class="item" @click="isConfirm = false">
          {{ $t("exchange.cancel") }}
        </div>
        <div class="item" @click="publishTraditionFun()">
          {{ $t("exchange.confirm") }}
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.ExchangePage {
  min-height: 100vh;
  max-height: 100vh;

  overflow-y: scroll;

  .searchDiv {
    display: flex;
    width: 85%;
    height: 40rem;
    justify-content: center;
    align-items: center;
    margin: auto;

    input {

      border-radius: 20px;
      font-size: 16rem;
      width: 100vw;
      height: 30rem;
    }
  }

  &::-webkit-scrollbar {
    display: none;
  }

  position: relative;

  >.top {
    background: #27222b;
    position: sticky;
    z-index: 10;
    top: 0;

    .topBarCom :deep(.topBar) {
      .search {
        margin-left: 10rem;
        background: #e6e6e6;
        border-radius: 16rem;

        display: none;
      }
    }

    .title {
      position: absolute;
      left: 0;
      right: 0;

      width: 70%;
      margin: 0 auto;

      color: #fff;
      font-size: 18rem;
      text-align: center;
    }

    .avatar {
      width: 32rem;
      height: 32rem;
      border-radius: 50%;
      margin-left: 16rem;
    }

    .info {
      font-size: 13rem;
      font-weight: 400;
      line-height: 18rem;
      color: #fff;

      display: flex;
      justify-content: center;
      padding-bottom: 12rem;

      >.balance {
        margin-right: 10rem;
      }
    }

    .moreBox {
      position: absolute;
      top: 65rem;
      right: 0;

      padding: 12rem 12rem 50rem;
      background: rgba(212, 212, 212, 0.9);

      border-radius: 12rem;

      >.item {
        display: flex;
        align-items: center;

        font-weight: 400;

        >.text {
          font-size: 16rem;
          line-height: 22rem;
          margin-right: 40rem;
        }

        >.num {
          width: 16rem;
          height: 16rem;

          text-align: center;
          font-size: 12rem;
          line-height: 16rem;
          color: #fff;

          background: #ff7878;
          border-radius: 50%;
        }
      }
    }
  }

  >.main {
    padding: 16rem 16rem;

    >.convert {
      display: flex;
      justify-content: space-between;
      align-items: center;

      &.reverse {
        flex-direction: row-reverse;
      }

      margin-bottom: 18rem;

      >.item {
        display: flex;
        align-items: center;

        flex: 1;

        >input {
          border: none;
        }

        >.title {
          font-size: 24rem;
          font-weight: 500;
          line-height: 34rem;
          color: rgba(100, 46, 142, 1);

          display: flex;
          align-items: center;

          &.currency {
            font-size: 14rem;
            font-weight: 400;
            line-height: 20rem;
            color: rgba(0, 0, 0, 1);
          }

          >img {
            width: 16rem;
            margin: 0 4rem;
          }
        }

        >input {
          flex: 1;
          margin: 0 10rem;
          height: 32rem;
          width: 64rem;

          text-align: center;
          border-bottom: 1rem solid #e6e6e6;

          font-size: 20rem;
          font-weight: 500;
          line-height: 28rem;
          color: rgba(51, 51, 51, 1);
        }
      }

      >.logo {
        width: 44rem;
        margin: 0 10rem;
      }
    }

    >.address {
      font-size: 16rem;
      font-weight: 400;
      line-height: 22rem;
      color: #666;

      width: 100%;
      margin-bottom: 24rem;

      display: flex;
      align-items: center;

      >input {
        flex: 1;
        margin: 0 10rem;
      }
    }

    >.submit {
      font-size: 16rem;
      font-weight: 500;
      line-height: 22rem;
      color: #fff;

      padding: 12rem;
      background: #642e8e;
      border-radius: 22rem;
      text-align: center;
    }
  }

  >.square {
    padding: 0 16rem 20rem;

    >.title {
      font-size: 16rem;
      font-weight: 500;
      line-height: 22rem;
      color: #333;

      // position: sticky;
      // top: 110rem;
      // z-index: 10;
      // background: #fff;

      margin-bottom: 16rem;
    }

    >.tabs {
      display: flex;
      align-items: center;
      justify-content: space-between;

      margin-bottom: 16rem;

      >.tab {
        display: flex;
        align-items: center;

        .item {
          font-size: 14rem;
          font-weight: 400;
          line-height: 20rem;
          color: #666;

          padding: 4rem 16rem;
          background: #e6e6e6;

          border-radius: 16rem;

          &:nth-of-type(1) {
            margin-right: 16rem;

            &.is_rtl {
              margin-right: 0rem;
              margin-left: 16rem;
            }
          }

          &.con {
            background: #ffc300;
            color: #fff;
          }
        }
      }

      >.choose {
        display: flex;
        align-items: center;

        font-size: 14rem;
        font-weight: 400;
        line-height: 20rem;
        color: #000;

        .type {
          margin-left: 6rem;
        }

        >img {
          width: 20rem;
          margin-left: 8rem;
        }
      }
    }
  }

  :deep(.isConfirm) {
    background: rgb(240, 240, 240);

    >.title {
      padding: 20rem 30rem;
      font-size: 18rem;
      border-bottom: 1rem solid #cacaca;
    }

    >.btn {
      display: flex;
      align-items: center;

      >.item {
        padding: 10rem 0;
        position: relative;
        text-align: center;
        font-size: 14rem;
        flex: 1;

        &:last-of-type {
          background: rgba(39, 34, 42, 0.9);
          color: #fff;
        }
      }
    }
  }
}
</style>